package com.yeskery.nut.extend.mcp.server.method;

import com.yeskery.nut.bean.ApplicationContext;
import com.yeskery.nut.extend.mcp.core.Resource;
import com.yeskery.nut.extend.mcp.core.ResourceType;
import com.yeskery.nut.extend.mcp.core.schema.ResourceSchema;
import com.yeskery.nut.extend.mcp.server.McpServerCapability;

import java.util.stream.Collectors;

/**
 * 资源列表方法处理器
 * @author sprout
 * 2025-04-17 15:20
 */
public class ResourcesListMethodHandler extends BaseListMethodHandler {

    /** 资源类型 */
    private final ResourceType resourceType;

    /**
     * 构造资源列表方法处理器
     * @param applicationContext  应用上下文
     * @param mcpServerCapability 服务能力
     * @param resourceType 资源类型
     */
    public ResourcesListMethodHandler(ApplicationContext applicationContext, McpServerCapability mcpServerCapability, ResourceType resourceType) {
        super(applicationContext, mcpServerCapability);
        this.resourceType = resourceType;
    }

    @Override
    protected Object getHandleResult(String cursor) {
        McpServerCapability mcpServerCapability = getMcpServerCapability();
        ResourceSchema.ListResourcesResult result = new ResourceSchema.ListResourcesResult();
        result.setResources(mcpServerCapability.getResources().stream().filter(r -> {
            if (resourceType == ResourceType.RESOURCE) {
                return r.getResource() instanceof ResourceSchema.Resource;
            } else {
                return r.getResource() instanceof ResourceSchema.ResourceTemplate;
            }
        }).skip(parseNumberCursor(cursor)).map(Resource::getResource).collect(Collectors.toList()));
        return result;
    }
}
